package com.lwt.codetop.graph;

// 200. 岛屿数量

/**
 * 思路：flood fill算法，遍历连通块然后进行标记
 */
public class NumberOfIslands {
    private static int N = 300 + 10;
    private static int res = 0;
    private static int n, m;
    private static boolean[][] st = new boolean[N][N];
    private static char[][] grid;
    public static void main(String[] args) {
        // 构建测试用例--->全局变量
        grid = new char[][] {
                {'1', '1', '0', '1', '0'},
                {'1', '1', '0', '1', '0'},
                {'1', '1', '0', '0', '0'},
                {'0', '0', '0', '0', '0'}
        };
        n = grid.length;
        m = grid[0].length;
        // 遍历网格，dfs统计连通块个数
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if(grid[i][j] == '1' && st[i][j] == false){
                    dfs(i, j);
                    res += 1;
                }
            }
        }
        System.out.println(res);
    }

    /**
     * dfs遍历连通块
     * @param x
     * @param y
     */
    private static void dfs(int x, int y) {
        int[] dx = {-1, 0, 1, 0};
        int[] dy = {0, 1, 0, -1};
        // 标记
        st[x][y] = true;
        for(int i = 0; i < 4; i ++){
            int a = x + dx[i], b = y + dy[i];
            if(a < 0 || a >= n || b < 0 || b >= m || st[a][b] == true || grid[a][b] != '1') continue;
            dfs(a, b);
        }
    }


}
